/*
 * File     : StructureByValueList.java
 * Created  : 25 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.structure;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.internal.MemoryAccess;
import com.googlecode.dni.type.NativeObject;
import com.googlecode.dni.type.NativeObjectList;
import com.googlecode.dni.type.Pointer;
import com.googlecode.dni.type.structure.Structure;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;


/**
 * Implementation of {@link NativeObjectList} for {@link Structure}s held by
 * value.
 *
 * @param <E>
 *            the element type
 *
 * @author Matthew Wilson
 */
final class StructureByValueList< E extends Structure > implements NativeObjectList< E >
{

    private final long pointer;

    private final int structureSize;

    private final E[] array;


    /**
     * Creates a new instance, allocating memory.
     *
     * @param structureType
     *            the structure type
     * @param factory
     *            the structure factory
     * @param structureSize
     *            the size of the structure
     * @param size
     *            the number of elements in the list
     */
    StructureByValueList( final Class< E > structureType,
                          final AbstractStructureFactory< E > factory,
                          final int structureSize,
                          final int size )
    {
        this.pointer = DniInternal.ALLOCATOR.allocate( size * (long) structureSize ).address();
        this.structureSize = structureSize;

        E[] castArray = createArray( this.pointer, structureType, factory, structureSize, size );
        this.array = castArray;
    }

    /**
     * Creates a new instance from an existing pointer.
     *
     * @param pointer
     *            the pointer
     * @param structureType
     *            the structure type
     * @param factory
     *            the structure factory
     * @param structureSize
     *            the size of the structure
     * @param size
     *            the number of elements in the list
     */
    StructureByValueList( final Pointer pointer,
                          final Class< E > structureType,
                          final AbstractStructureFactory< E > factory,
                          final int structureSize,
                          final int size )
    {
        this.pointer = pointer.address();
        this.structureSize = structureSize;

        E[] castArray = createArray( this.pointer, structureType, factory, structureSize, size );
        this.array = castArray;
    }


    /**
     * Creates from a region.
     *
     * @param parent
     *            the parent
     * @param fromIndex
     *            index of the first element (inclusive)
     * @param toIndex
     *            index of the last element (exclusive)
     */
    private StructureByValueList( final StructureByValueList< E > parent, final int fromIndex, final int toIndex )
    {
        if ( fromIndex < 0 || toIndex > parent.array.length || fromIndex > toIndex )
        {
            throw new IndexOutOfBoundsException();
        }

        this.pointer = parent.pointer + ( fromIndex * (long) parent.getStructureSize() );
        this.structureSize = parent.structureSize;
        this.array = Arrays.copyOfRange( parent.array, fromIndex, toIndex );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Pointer pointer()
    {
        return Pointer.fromAddress( this.pointer );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isSameObject( final NativeObject other )
    {
        return other instanceof StructureByValueList && other.pointer().address() == this.pointer;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int size()
    {
        return this.array.length;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isEmpty()
    {
        return this.array.length == 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean contains( final Object o )
    {
        return indexOf( o ) >= 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Iterator< E > iterator()
    {
        return new StructureListIterator( 0 );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object[] toArray()
    {
        return Arrays.copyOf( this.array, this.array.length, Object[].class );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public < T > T[] toArray( final T[] a )
    {
        if ( a.length < this.array.length )
        {
            @SuppressWarnings( "unchecked" )
            T[] copy = (T[]) Arrays.copyOf( this.array, this.array.length, a.getClass() );
            return copy;
        }

        System.arraycopy( this.array, 0, a, 0, this.array.length );

        if ( a.length > this.array.length )
        {
            a[ this.array.length ] = null;
        }

        return a;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean add( final E e )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean remove( final Object o )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean containsAll( final Collection< ? > c )
    {
        for ( final Object object : c )
        {
            if ( !contains( object ) )
            {
                return false;
            }
        }
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean addAll( final Collection< ? extends E > c )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean addAll( final int index, final Collection< ? extends E > c )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean removeAll( final Collection< ? > c )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean retainAll( final Collection< ? > c )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void clear()
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public E get( final int index )
    {
        return this.array[ index ];
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public E set( final int index, final E element )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void add( final int index, final E element )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public E remove( final int index )
    {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int indexOf( final Object o )
    {
        for ( int i = 0; i < this.array.length; i++ )
        {
            if ( this.array[ i ].equals( o ) )
            {
                return i;
            }
        }
        return -1;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int lastIndexOf( final Object o )
    {
        for ( int i = this.array.length - 1; i >= 0 ; i-- )
        {
            if ( this.array[ i ].equals( o ) )
            {
                return i;
            }
        }
        return -1;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ListIterator< E > listIterator()
    {
        return new StructureListIterator( 0 );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ListIterator< E > listIterator( final int index )
    {
        return new StructureListIterator( index );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public NativeObjectList< E > subList( final int fromIndex, final int toIndex )
    {
        return new StructureByValueList< E >( this, fromIndex, toIndex );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void free()
    {
        MemoryAccess.ALLOCATOR.free( pointer() );
    }

    /**
     * {@inheritDoc}
     */
    @SuppressFBWarnings( value = "NSE_NON_SYMMETRIC_EQUALS",
                         justification = "java.util.List defines its own rules" )
    @Override
    public boolean equals( final Object obj )
    {
        if ( !( obj instanceof List< ? >) )
        {
            return false;
        }
        if ( obj == this )
        {
            return true;
        }
        if ( obj instanceof StructureByValueList< ? > )
        {
            return Arrays.equals( this.array, ( (StructureByValueList< ? >) obj ).array );
        }

        List< ? > other = (List< ? >) obj;
        if ( other.size() != this.array.length )
        {
            return false;
        }

        Iterator< ? > iterator = other.iterator();
        for ( int i = 0; i < this.array.length; i++ )
        {
            if ( !this.array[ i ].equals( iterator.next() ) )
            {
                return false;
            }
        }

        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode()
    {
        return Arrays.hashCode( this.array );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString()
    {
        return Arrays.toString( this.array );
    }

    private static < E extends Structure >
    E[] createArray( final long pointer,
                     final Class< E > structureType,
                     final AbstractStructureFactory< E > factory,
                     final int structureSize,
                     final int size )
    {
        @SuppressWarnings( "unchecked" )
        E[] castArray = (E[]) Array.newInstance( structureType, size );
        for ( int i = 0; i < size; i++ )
        {
            castArray[ i ] = factory.fromPointer( pointer + ( i * (long) structureSize ) );
        }
        return castArray;
    }

    private int getStructureSize()
    {
        return this.structureSize;
    }


    private final class StructureListIterator implements ListIterator< E >
    {
        private int index;

        StructureListIterator( final int index )
        {
            this.index = index;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean hasNext()
        {
            return this.index < StructureByValueList.this.array.length;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public E next()
        {
            if ( !hasNext() )
            {
                throw new NoSuchElementException();
            }

            E element = StructureByValueList.this.array[ this.index ];
            this.index++;
            return element;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean hasPrevious()
        {
            return this.index > 0;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public E previous()
        {
            if ( !hasPrevious() )
            {
                throw new NoSuchElementException();
            }

            this.index--;
            E element = StructureByValueList.this.array[ this.index ];
            return element;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public int nextIndex()
        {
            return this.index;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public int previousIndex()
        {
            return this.index - 1;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void remove()
        {
            throw new UnsupportedOperationException();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void set( final E e )
        {
            throw new UnsupportedOperationException();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void add( final E e )
        {
            throw new UnsupportedOperationException();
        }
    }

}
